﻿#include "qtcamera.h"
#include <QApplication>
#include <QtWidgets>
#include <QHBoxLayout>
#include <QVBoxLayout>

#define FONT_SIZE 20

qtCamera::qtCamera()
{
    QBoxLayout *vLayout = new QVBoxLayout();
    const QRect availableGeometry = QApplication::desktop()->availableGeometry(this);
    QFont font;
    font.setPixelSize(FONT_SIZE);
    resize(availableGeometry.width(), availableGeometry.height());

    //可用相机列表
    const QList<QCameraInfo> availableCameras = QCameraInfo::availableCameras();
    for (const QCameraInfo &cameraInfo : availableCameras)
    {
        qDebug() << cameraInfo.description();
        if (cameraInfo.description().contains("USB", Qt::CaseSensitive) || cameraInfo.description().contains("UVC", Qt::CaseSensitive))
        {
            //USB摄像头
            QPushButton *camera = new QPushButton;
            camera->setText(cameraInfo.description());
            camera->setFont(font);
            camera->setCheckable(true);
            if (cameraInfo == QCameraInfo::defaultCamera())
            {
                camera->setDefault(true);
            }
            else
            {
                camera->setDefault(false);
            }

            //启动相机
            connect(camera, SIGNAL(clicked(bool)), this, SLOT(on_cameraClick()));
            vLayout->addWidget(camera);

            m_cameraInfo = cameraInfo;
            break;
        }
    }

    //退出按钮
    QPushButton *exitButton = new QPushButton;
    exitButton->setText(tr("Exit"));
    exitButton->setFont(font);
    connect(exitButton, SIGNAL(clicked(bool)), this, SLOT(on_exitClicked()));

    //按钮垂直布局
    vLayout->addWidget(exitButton);
    vLayout->setAlignment(Qt::AlignTop);

    //创建取景器
    m_viewfinder = new QCameraViewfinder();

    //整体水平布局
    QBoxLayout *hlayout = new QHBoxLayout;
    hlayout->setMargin(0);
    hlayout->addWidget(m_viewfinder);
    hlayout->addLayout(vLayout);
    hlayout->setStretch(0,10);
    hlayout->setStretch(1,1);
    hlayout->setContentsMargins(10, 10, 10, 10);

    QWidget *widget = new QWidget;
    widget->setLayout(hlayout);
    setCentralWidget(widget);
    setWindowFlags(Qt::FramelessWindowHint);
}

//切换相机
void qtCamera::on_cameraClick()
{
    //创建摄像头对象
    m_camera = new QCamera(m_cameraInfo);

    //配置摄像头的模式--捕获静止图像
    QCamera::CaptureModes captureMode = QCamera::CaptureStillImage;
    if (m_camera->isCaptureModeSupported(captureMode))
    {
        m_camera->unload();
        m_camera->setCaptureMode(captureMode);
        //设置取景器显示
        m_camera->setViewfinder(m_viewfinder);
        //启动摄像头
        m_camera->start();
    }
}

void qtCamera::on_exitClicked()
{
    qApp->exit(0);
}

//https://lequ7.com/guan-yu-cqtopencv-diao-yong-camera-de-jian-dan-ying-yong.html
